package cn.cdutetc.foxwatch.ws;

import cn.cdutetc.foxwatch.config.GetHttpSessionConfig;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 王勇
 * @ClassName： test
 * @ClassPath： cn.cdutetc.foxwatch.ws.test
 * @Description：用户聊天接口未开发 ws://localhost:8089/chat/user
 * @date 2024/10/3 00:21
 */
@Component
@ServerEndpoint(value = "/chat/user", configurator = GetHttpSessionConfig.class)
public class ChatEndpoint {

    private static final Map<String, Session> onlineUsers = new ConcurrentHashMap<>();

    private HttpSession httpSession;

    private static String getSessionUserId(Session session) {
        List<String> useList = session.getRequestParameterMap().get("userId");
        if (useList != null) {
            return useList.get(0);
        } else {
            return null;
        }
    }

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        System.out.println("WebSocket opened");
        String userId = getSessionUserId(session);
        onlineUsers.putIfAbsent(userId, session);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println(message);
        Message msg = JSON.parseObject(message, Message.class);
        String receiver = msg.getReceiver();
        if (onlineUsers.get(receiver) != null) {
            System.out.println("Sending message to " + receiver);
            Session receiverSession = onlineUsers.get(receiver);
            receiverSession.getBasicRemote().sendText("data: " + msg.getMessage());
        } else {
            System.out.println("User " + receiver + " is not online");
        }
    }

    @OnClose
    public void onClose(Session session) {
        for (Map.Entry<String, Session> entry : onlineUsers.entrySet()) {
            if (entry.getValue().getId().equals(session.getId())) {
                onlineUsers.remove(entry.getKey());
                break;
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("WebSocket error: " + session.getId());
        throwable.printStackTrace();
    }

    private void broadcastAllUsers(String message) {
        for (Session userSession : onlineUsers.values()) {
            try {
                if (userSession.isOpen()) {
                    userSession.getBasicRemote().sendText(message);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}